package com.dexafree.materiallistviewexample.slice;

import com.dexafree.materiallist.card.Card;
import com.dexafree.materiallist.card.CardProvider;
import com.dexafree.materiallist.card.OnActionClickListener;
import com.dexafree.materiallist.card.action.TextViewAction;
import com.dexafree.materiallist.card.action.WelcomeButtonAction;
import com.dexafree.materiallist.card.provider.ListCardProvider;
import com.dexafree.materiallist.listeners.OnDismissCallback;
import com.dexafree.materiallist.listeners.RecyclerItemClickListener;
import com.dexafree.materiallist.view.MaterialListView;
import com.dexafree.materiallistviewexample.MyPopuDialog;
import com.dexafree.materiallistviewexample.ResourceTable;
import com.dexafree.materiallistviewexample.provider.ArrayProvider;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.RequestCreator;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.Element;
import ohos.agp.components.element.PixelMapElement;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.utils.TextAlignment;
import ohos.agp.window.dialog.PopupDialog;
import ohos.agp.window.dialog.ToastDialog;
import ohos.app.Context;
import ohos.global.resource.NotExistException;
import ohos.global.resource.ResourceManager;
import ohos.global.resource.WrongTypeException;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;
import ohos.media.image.common.Rect;
import ohos.media.image.common.Size;
import ohos.utils.net.Uri;
import utils.LogUtil;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class MainAbilitySlice extends AbilitySlice implements Component.ClickedListener {
    private Context mContext;
    private MaterialListView mListView;
    private Component view;
    private MyPopuDialog popupDialog;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_activity_main_ohos);
        mContext = this;
        findComponentById(ResourceTable.Id_image_topbar).setClickedListener(this);
        mListView = (MaterialListView) findComponentById(ResourceTable.Id_material_listview);
//        mListView.setItemAnimator(new SlideInLeftAnimator());
//        mListView.getItemAnimator().setAddDuration(300);
//        mListView.getItemAnimator().setRemoveDuration(300);

        final Image emptyView = (Image) findComponentById(ResourceTable.Id_imageView);
        emptyView.setScaleMode(Image.ScaleMode.INSIDE);
        mListView.setEmptyView(emptyView);
        Picasso.get()
                .load("https://www.skyverge.com/wp-content/uploads/2012/05/github-logo.png")
                .resize(100, 100)
                .centerInside()
                .into(emptyView);

        // Fill the array withProvider mock content
        fillArray();

        // Set the dismiss listener
        mListView.setOnDismissCallback(new OnDismissCallback() {
            @Override
            public void onDismiss(Card card, int position) {
                // Show a toast
                new ToastDialog(mContext).setText("You have dismissed a " + card.getTag()).setDuration(2000).show();
            }
        });
        // Add the ItemTouchListener
        mListView.addOnItemTouchListener(new RecyclerItemClickListener.OnItemClickListener() {
            @Override
            public void onItemClick(Card card, int position) {
                LogUtil.debug("CARD_TYPE", "" + card.getTag());
            }

            @Override
            public void onItemLongClick(Card card, int position) {
                LogUtil.debug("LONG_CLICK", "" + card.getTag());
            }
        });

    }


    private void fillArray() {
        List<Card> cards = new ArrayList<>();
        for (int i = 0; i < 35; i++) {
            cards.add(getRandomCard(i));
        }
        mListView.getItemProvider().addAll(cards);
    }

    public static String getPathById(Context context, int id) {
        String path = "";
        if (context == null) {
            return path;
        }
        ResourceManager manager = context.getResourceManager();
        if (manager == null) {
            return path;
        }
        try {
            path = manager.getMediaPath(id);
        } catch (IOException e) {
            LogUtil.error("cpf", "getPathById -> IOException");
        } catch (NotExistException e) {
            LogUtil.error("cpf", "getPathById -> NotExistException");
        } catch (WrongTypeException e) {
            LogUtil.error("cpf", "getPathById -> WrongTypeException");
        }
        return path;

    }

    public static PixelMap getPixelMapFromRes(Context context, int res) {
        InputStream stream = null;
        try {
            stream = context.getResourceManager().getResource(res);
            ImageSource.SourceOptions sourceOptions = new ImageSource.SourceOptions();
            sourceOptions.formatHint = "image/png";
            ImageSource imageSource = ImageSource.create(stream, sourceOptions);
            ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
            decodingOptions.desiredSize = new Size(0, 0);
            decodingOptions.desiredRegion = new Rect(0, 0, 0, 0);
            decodingOptions.desiredPixelFormat = PixelFormat.ARGB_8888;

            return imageSource.createPixelmap(decodingOptions);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (stream != null) {
                    stream.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return null;
    }

    private Card getRandomCard(final int position) {
        String title = "Card number " + (position + 1);
        String description = "Lorem ipsum dolor sit amet";
        ShapeElement shapeElement = new ShapeElement();
        switch (position % 7) {
            case 0: {
                try {
                    return new Card.Builder(mContext)
                            .setTag("SMALL_IMAGE_CARD")
                            .setDismissible()
                            .withProvider(new CardProvider())
                            .setLayout(com.dexafree.materiallist.ResourceTable.Layout_material_small_image_card_ohos)
                            .setTitle(title)
                            .setDescription(description)
                            .setDrawable(ResourceTable.Media_sample_android)
                            .setDrawableConfiguration(new CardProvider.OnImageConfigListener() {
                                @Override
                                public void onImageConfigure(final RequestCreator requestCreator) {
                                    requestCreator.rotate(position * 90.0f)
                                            .resize(150, 150)
                                            .centerCrop();
                                }
                            })
                            .endConfig()
                            .build();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            case 1: {
                return new Card.Builder(this)
                        .setTag("BIG_IMAGE_CARD")
                        .withProvider(new CardProvider())
                        .setLayout(com.dexafree.materiallist.ResourceTable.Layout_material_big_image_card_layout_ohos)
                        .setTitle(title)
                        .setSubtitle(description)
                        .setSubtitleGravity(TextAlignment.END)
                        .setDrawable("https://assets-cdn.github.com/images/modules/logos_page/GitHub-Mark.png")
                        .setDrawableConfiguration(new CardProvider.OnImageConfigListener() {
                            @Override
                            public void onImageConfigure(final RequestCreator requestCreator) {
                                requestCreator.rotate(position * 45.0f)
                                        .resize(200, 200)
                                        .centerCrop();
                            }
                        })
                        .endConfig()
                        .build();
            }
            case 2: {
                final CardProvider provider = new Card.Builder(this)
                        .setTag("BASIC_IMAGE_BUTTON_CARD")
                        .setDismissible()
                        .withProvider(new CardProvider<>())
                        .setLayout(com.dexafree.materiallist.ResourceTable.Layout_material_basic_image_buttons_card_layout_ohos)
                        .setTitle(title)
                        .setTitleGravity(TextAlignment.END)
                        .setDescription(description)
                        .setDescriptionGravity(TextAlignment.END)
                        .setDrawable(ResourceTable.Media_dog)
                        .setDrawableConfiguration(new CardProvider.OnImageConfigListener() {
                            @Override
                            public void onImageConfigure(RequestCreator requestCreator) {
                                requestCreator.fit();
                            }
                        })
                        .addAction(ResourceTable.Id_left_text_button, new TextViewAction(this)
                                .setText("left")
                                .setTextResourceColor(ResourceTable.Color_black_button)
                                .setListener(new OnActionClickListener() {
                                    @Override
                                    public void onActionClicked(Component view, Card card) {
                                        showDialog("You have pressed the left button");
                                        card.getProvider().setTitle("CHANGED ON RUNTIME");
                                    }
                                }))
                        .addAction(ResourceTable.Id_right_text_button, new TextViewAction(this)
                                .setText("right")
                                .setTextResourceColor(ResourceTable.Color_orange_button)
                                .setListener(new OnActionClickListener() {
                                    @Override
                                    public void onActionClicked(Component view, Card card) {
                                        showDialog("You have pressed the right button on card " + card.getProvider().getTitle());
                                        card.dismiss();
                                    }
                                }));

                if (position % 2 == 0) {
                    provider.setDividerVisible(true);
                }

                return provider.endConfig().build();
            }
            case 3: {
                final CardProvider provider = new Card.Builder(this)
                        .setTag("BASIC_BUTTONS_CARD")
                        .setDismissible()
                        .withProvider(new CardProvider())
                        .setLayout(ResourceTable.Layout_material_basic_buttons_card_ohos)
                        .setTitle(title)
                        .setDescription(description)
                        .addAction(ResourceTable.Id_left_text_button, new TextViewAction(this)
                                .setText("left")
                                .setTextResourceColor(ResourceTable.Color_black_button)
                                .setListener(new OnActionClickListener() {
                                    @Override
                                    public void onActionClicked(Component view, Card card) {
                                        showDialog("You have pressed the left button");
                                    }
                                }))
                        .addAction(ResourceTable.Id_right_text_button, new TextViewAction(this)
                                .setText("right")
                                .setTextResourceColor(ResourceTable.Color_accent_material_dark)
                                .setListener(new OnActionClickListener() {
                                    @Override
                                    public void onActionClicked(Component view, Card card) {
                                        showDialog("You have p the right button on card " + card.getProvider().getTitle());
                                    }
                                }));

                if (position % 2 == 0) {
                    provider.setDividerVisible(true);
                }

                return provider.endConfig().build();
            }
            case 4: {
                final CardProvider provider = new Card.Builder(this)
                        .setTag("WELCOME_CARD")
                        .setDismissible()
                        .withProvider(new CardProvider())
                        .setLayout(ResourceTable.Layout_material_welcome_card_layout_ohos)
                        .setTitle("Welcome Card")
                        .setTitleColor(Color.WHITE.getValue())
                        .setDescription("I am the description")
                        .setDescriptionColor(Color.WHITE.getValue())
                        .setSubtitle("My subtitle!")
                        .setSubtitleColor(Color.WHITE.getValue())
                        .setBackgroundColor(Color.BLUE.getValue())
                        .addAction(ResourceTable.Id_ok_button, new WelcomeButtonAction(this)
                                .setText("Okay!")
                                .setTextColor(Color.WHITE.getValue())
                                .setListener(new OnActionClickListener() {
                                    @Override
                                    public void onActionClicked(Component view, Card card) {
                                        showDialog("Welcome!");
                                    }
                                }));

                if (position % 2 == 0) {
                    provider.setBackgroundResourceColor(ResourceTable.Color_accent_material_dark);
                }

                return provider.endConfig().build();
            }
            case 5: {
                ArrayProvider<String> adapter = new ArrayProvider<>(this, ResourceTable.Layout_simple_list_item_1_ohos);
                adapter.add("Hello");
                adapter.add("World");
                adapter.add("!");

                return new Card.Builder(this)
                        .setTag("LIST_CARD")
                        .setDismissible()
                        .withProvider(new ListCardProvider())
                        .setLayout(ResourceTable.Layout_material_list_card_layout_ohos)
                        .setTitle("List Card")
                        .setDescription("Take a list")
                        .setAdapter(adapter)
                        .endConfig()
                        .build();
            }
            default: {
                final CardProvider provider = new Card.Builder(this)
                        .setTag("BIG_IMAGE_BUTTONS_CARD")
                        .setDismissible()
                        .withProvider(new CardProvider())
                        .setLayout(ResourceTable.Layout_material_image_with_buttons_card_ohos)
                        .setTitle(title)
                        .setDescription(description)
                        .setDrawable(ResourceTable.Media_photo)
                        .addAction(ResourceTable.Id_left_text_button, new TextViewAction(this)
                                .setText("add card")
                                .setTextResourceColor(ResourceTable.Color_black_button)
                                .setListener(new OnActionClickListener() {
                                    @Override
                                    public void onActionClicked(Component view, Card card) {
                                        LogUtil.debug("ADDING", "CARD");

                                        mListView.getItemProvider().add(generateNewCard());
                                        showDialog("Added new card");
                                    }
                                }))
                        .addAction(ResourceTable.Id_right_text_button, new TextViewAction(this)
                                .setText("right button")
                                .setTextResourceColor(ResourceTable.Color_accent_material_dark)
                                .setListener(new OnActionClickListener() {
                                    @Override
                                    public void onActionClicked(Component view, Card card) {
                                        showDialog("You have pressed the right button");
                                    }
                                }));

                if (position % 2 == 0) {
                    provider.setDividerVisible(true);
                }

                return provider.endConfig().build();
            }
        }
    }

    private void showDialog(String text) {
        ToastDialog toastDialog = new ToastDialog(mContext);
        toastDialog.setText(text).setDuration(2000);
        Text toastText = (Text) toastDialog.getComponent();
        toastText.setMultipleLine(true);
        ShapeElement toastBackground = new ShapeElement();
        toastBackground.setRgbColor(new RgbColor(24, 196, 124));
        toastBackground.setCornerRadius(20f);
        toastDialog.show();
        toastDialog.show();
    }

    private Card generateNewCard() {
        return new Card.Builder(this)
                .setTag("BASIC_IMAGE_BUTTONS_CARD")
                .withProvider(new CardProvider())
                .setLayout(ResourceTable.Layout_material_basic_image_buttons_card_layout_ohos)
                .setTitle("I'm new")
                .setDescription("I've been generated on runtime!")
                .setDrawable(ResourceTable.Media_dog)
                .endConfig()
                .build();
    }

    private void addMockCardAtStart() {
        mListView.getItemProvider().addAtStart(new Card.Builder(this)
                .setTag("BASIC_IMAGE_BUTTONS_CARD")
                .setDismissible()
                .withProvider(new CardProvider())
                .setLayout(ResourceTable.Layout_material_basic_image_buttons_card_layout_ohos)
                .setTitle("Hi there")
                .setDescription("I've been added on top!")
                .addAction(ResourceTable.Id_left_text_button, new TextViewAction(this)
                        .setText("left")
                        .setTextResourceColor(ResourceTable.Color_black_button))
                .addAction(ResourceTable.Id_right_text_button, new TextViewAction(this)
                        .setText("right")
                        .setTextResourceColor(ResourceTable.Color_orange_button))
                .setDrawable(ResourceTable.Media_dog)
                .endConfig()
                .build());
    }

    @Override
    public void onClick(Component component) {
        switch (component.getId()) {
            case ResourceTable.Id_image_topbar:
                if (view == null) {
                    view = LayoutScatter.getInstance(mContext).parse(ResourceTable.Layout_layout_popu_dialog, null, true);
                }
                popupDialog = new MyPopuDialog(this, view, this);
                popupDialog.setAutoClosable(true);
                popupDialog.setAlignment(LayoutAlignment.RIGHT | LayoutAlignment.TOP);
                if (!popupDialog.isShowing()) {
                    popupDialog.show();
                }
                break;
            case ResourceTable.Id_tv_clear:
                mListView.getItemProvider().clearAll();
                if (popupDialog != null && popupDialog.isShowing()) {
                    popupDialog.hide();
                }
                break;
            case ResourceTable.Id_tv_add_satrt:
                addMockCardAtStart();
                if (popupDialog != null && popupDialog.isShowing()) {
                    popupDialog.hide();
                }
                break;
            case ResourceTable.Id_tv_setting:
                if (popupDialog != null && popupDialog.isShowing()) {
                    popupDialog.hide();
                }
                break;
        }
    }
}